﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;

namespace HRM
{
    public partial class frmChooseEmployeeList : DockContent
    {
        EmployeeClient wcfEmployee;
        //BranchClient wcfBranch;
        //DepartmentClient wcfDepartment;
        DialogResult dlgResult;
        RoleRightInfo listRole;
        int itemCount = 0;
        int pageSize = UIParamater.pageSize;
        int totalPage = 0;
        int currPage = 0;
        int employeeID = 0;
        int department_ID;
        int branch_ID;
        DateTime _date;
        string _month;
        string _year;
        bool _IsBHTN;
        bool _PhatSinhBH;
        bool _IsFactor;
        string _selectedID = ",";
        string[] _emplID = null;
        private string _FullName;
        public string FullName
        {
            get { return _FullName; }
            set { _FullName = value; }
        }

        private int _EmployeeID;
        public int EmployeeID
        {
            get { return _EmployeeID; }
            set { _EmployeeID = value; }
        }
        string _SIBookNo;
        public string SIBookNo
        {
            get { return _SIBookNo; }
            set { _SIBookNo = value; }
        }
        bool _ChangeDepartment = false;
        PositionDetailInfo[] _PDInfo;
        public frmChooseEmployeeList(bool IsBHTN, string month, string year, RoleRightInfo _listRole)
        {
            InitializeComponent();
            LoadLanguage();
            _month = month;
            _year = year;
            _IsBHTN = IsBHTN;
            dlgResult = DialogResult.Cancel;
            wcfEmployee = Service.Employee();
            txtKeyWord.Focus();
            listRole = _listRole;
            BuildVoucherGrid();
            UISetting.LoadTreeView3(ref tvBranch);
            LoadData();
        }

        public frmChooseEmployeeList(RoleRightInfo _listRole, bool PhatSinhBH, bool IsFactor, bool ChangeDepartment)
        {
            InitializeComponent();
            //LoadLanguage();
            dlgResult = DialogResult.Cancel;
            wcfEmployee = Service.Employee();
            listRole = _listRole;
            _PhatSinhBH = PhatSinhBH;
            _IsFactor = IsFactor;
            _ChangeDepartment = ChangeDepartment;
            if (_ChangeDepartment)
            {
                btnNew.Text = "Chọn phòng ban";
                ChkCheckAll.Visible = true;
            }
            else
                ChkCheckAll.Visible = false;
            BuildVoucherGrid();
            UISetting.LoadTreeView3(ref tvBranch);
            LoadData();
            txtKeyWord.Focus();
        }

        private void LoadLanguage()
        {
            this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip2);
        }

        private void BuildVoucherGrid()
        {
            dgvEmployeeList.Columns.Clear();
            //Thêm cột Checkbox
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col.Name = "Check";
            col.HeaderText = "Chọn";
            col.Width = 30;
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvEmployeeList.Columns.Add(col);
            col.Visible = _ChangeDepartment;
            //col.ReadOnly = false;
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_ReligionID", "Mã dân tộc", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_EthlicID", "Mã tôn giáo", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "RowNumber", UpdateUI.GetString("stt"), "C", 30, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Code", UpdateUI.GetString("manhanvien"), "L", 120, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "FullName", UpdateUI.GetString("hovaten"), "L", 150, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Position_Name", UpdateUI.GetString("chucvu"), "L", 150, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Department_Name", "Phòng ban", "", 130, true, true);
            // UISetting.AddColumn(ref dgvEmployeeList, "Grade_Name", UpdateUI.GetString("nganhchucdanh"), "", 300, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_DateOfBirth", UpdateUI.GetString("ngaysinh"), "C", 120, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Sex", UpdateUI.GetString("gioitinh"), "C", 120, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_SIBookNo", "Số sổ BH", "", 300, true, true);

        }


        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void LoadData()
        {
           // FormGlobals.App_ProgressShow(delegate()
           //{

               DataSet ds = wcfEmployee.Employee_GetList(out itemCount, branch_ID, department_ID, UISetting.GetKeyWord(txtKeyWord.Text.Trim()), "", "", currPage, pageSize);
               int n = ds.Tables[0].Rows.Count;
               PageIndex();
               dgvEmployeeList.Rows.Clear();
               for (int i = 0; i < n; i++)
               {
                   dgvEmployeeList.Rows.Insert(i, 1);
                   dgvEmployeeList.Columns["FullName"].Frozen = true;
                   dgvEmployeeList.Rows[i].Cells["Employee_ID"].Value = ds.Tables[0].Rows[i]["Employee_ID"].ToString();
                   dgvEmployeeList.Rows[i].Cells["Employee_ReligionID"].Value = ds.Tables[0].Rows[i]["Employee_ReligionID"].ToString();
                   dgvEmployeeList.Rows[i].Cells["Employee_EthlicID"].Value = ds.Tables[0].Rows[i]["Employee_EthlicID"].ToString();
                   dgvEmployeeList.Rows[i].Cells["RowNumber"].Value = ds.Tables[0].Rows[i]["RowNumber"].ToString();
                   // dgvEmployeeList.Rows[i].Cells["Employee_CardNo"].Value = ds.Tables[0].Rows[i]["Employee_CardNo"].ToString();
                   dgvEmployeeList.Rows[i].Cells["Employee_Code"].Value = ds.Tables[0].Rows[i]["Employee_Code"].ToString();
                   dgvEmployeeList.Rows[i].Cells["FullName"].Value = ds.Tables[0].Rows[i]["Employee_FullName"].ToString();

                   dgvEmployeeList.Rows[i].Cells["Position_Name"].Value = ds.Tables[0].Rows[i]["Position_Name"].ToString();
                   //dgvEmployeeList.Rows[i].Cells["Grade_Name"].Value = ds.Tables[0].Rows[i]["Grade_Name"].ToString();
                   dgvEmployeeList.Rows[i].Cells["Department_Name"].Value = ds.Tables[0].Rows[i]["Department_Name"].ToString();

                   dgvEmployeeList.Rows[i].Cells["Employee_DateOfBirth"].Value
                       = ds.Tables[0].Rows[i]["Employee_DateOfBirth"] == DBNull.Value ? ""
                       : Convert.ToDateTime(ds.Tables[0].Rows[i]["Employee_DateOfBirth"]).ToString("dd/MM/yyyy");
                   dgvEmployeeList.Rows[i].Cells["Employee_Sex"].Value = ds.Tables[0].Rows[i]["Employee_Sex"].ToString();

                   dgvEmployeeList.Rows[i].Cells["Employee_SIBookNo"].Value = ds.Tables[0].Rows[i]["Employee_SIBookNo"].ToString();
                   if (_selectedID.Contains("," + ds.Tables[0].Rows[i]["Employee_ID"].ToString() + ","))
                       dgvEmployeeList.Rows[i].Cells["Check"].Value = true;
                   else
                       dgvEmployeeList.Rows[i].Cells["Check"].Value = false;
               }
               dgvEmployeeList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
           //}, "Đang tải danh sách");
        }

        //private void btnNew_Click(object sender, EventArgs e)
        //{
        //    if (!listRole.Create)
        //    {
        //        Program.taskbarNotifier.Show( UpdateUI.GetString("canhbao"), UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
        //        return;
        //    }
        //    frmEmployeeInfo f = new frmEmployeeInfo(0, listRole);
        //    if (f.ShowDialog(this) == DialogResult.OK)
        //    {
        //        LoadData();
        //    }
        //}
        private void GetSelectedID()
        {
            dgvEmployeeList.EndEdit();
            foreach (DataGridViewRow row in dgvEmployeeList.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    if (!_selectedID.Contains("," + row.Cells["Employee_ID"].Value.ToString() + ","))
                        _selectedID += row.Cells["Employee_ID"].Value.ToString() + ",";
                }
                else
                {
                    string sOld = "," + row.Cells["Employee_ID"].Value.ToString() + ",";
                    if (_selectedID.Contains(sOld))
                        _selectedID = _selectedID.Replace(sOld, ",");
                }
            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            currPage = 0;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            if (currPage > 0)
                currPage--;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            if (totalPage != 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void dgvEmployeeList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (_month != null)
            {
                string _day = DateTime.Now.Day.ToString("00");
                _date = DateTime.ParseExact(_day + "/" + _month + "/" + _year, "dd/MM/yyyy", null);
                employeeID = Convert.ToInt32(dgvEmployeeList.SelectedRows[0].Cells["Employee_ID"].Value);
                if (!_IsBHTN)
                {
                    IssueInsBookClient wcfIssue = Service.IssueInsBook();
                    IssueInsBookInfo _IssueInfo = new IssueInsBookInfo();
                    _IssueInfo.Date = _date;
                    _IssueInfo.EmployeeID = employeeID;
                    if (wcfIssue.IssueInsBook_CheckExist(employeeID, _date) == 0)
                    {
                        _IssueInfo.ID = wcfIssue.IssueInsBook_Insert(_IssueInfo);
                        _IssueInfo.Date = _date;

                        if (_IssueInfo.ID > 0)
                        {
                            Program.taskbarNotifier.Show(UpdateUI.GetString("canhbao"), "Thêm cán bộ thành công!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                            dlgResult = DialogResult.OK;
                        }
                    }
                    else
                    {
                        Program.taskbarNotifier.Show(UpdateUI.GetString("canhbao"), "Cán bộ này đã đăng ký.\nHãy chọn cán bộ khác!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        dlgResult = DialogResult.Cancel;
                    }
                }
                else
                {
                    //UnemployedInsClient wcfUnemployedIns = Service.UnemployedIns();
                    //UnemployedInsInfo _UnemployedInsInfo = new UnemployedInsInfo();
                    //_UnemployedInsInfo.Date = _date;
                    //_UnemployedInsInfo.EmployeeID = employeeID;
                    //if (wcfUnemployedIns.UnemployedIns_CheckExist(employeeID, _date) == 0)
                    //{
                    //    _UnemployedInsInfo.ID = wcfUnemployedIns.UnemployedIns_Insert(_UnemployedInsInfo);
                    //    if (_UnemployedInsInfo.ID > 0)
                    //    {
                    //        Program.taskbarNotifier.Show(UpdateUI.GetString("canhbao"), "Thêm cán bộ thành công!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    //        dlgResult = DialogResult.OK;
                    //    }
                    //}
                    //else
                    //{
                    //    Program.taskbarNotifier.Show(UpdateUI.GetString("canhbao"), "Cán bộ này đã đăng ký.\nHãy chọn cán bộ khác!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    //    dlgResult = DialogResult.Cancel;
                    //}
                }
            }
            else if (_ChangeDepartment)
            {
                frmDepart fdept = new frmDepart();
                if (fdept.ShowDialog(this) == DialogResult.OK)
                {
                    //_selectedID = _selectedID.Substring(1, _selectedID.Length - 1);
                    _emplID = _selectedID.Split(',');


                    PositionDetailInfo _Info = new PositionDetailInfo();
                    PositionDetailClient _wcfPD = Service.PositionDetail();

                    //
                     LabourContractInfo _lbInfo = new LabourContractInfo();
                    LabourContractClient _wcfLC = new LabourContractClient();
                    //

                    for (int i = 0; i < _emplID.Length; i++)
                    {
                        if (_emplID[i].Length > 0)
                        {
                            _Info = _wcfPD.PositionDetail_GetInfo(Convert.ToInt32(_emplID[i]));
                            _Info.DepartmentID = fdept.DepartmentID;

                            //hiepdh: 200815
                            //Sửa lại ko lưu quá trình theo phòng ban nữa, chỉ cần 1 phòng ban mới nhất phụ vụ bảo hiểm
                            if (_Info.ID == 0)
                                _wcfPD.PositionDetail_Insert(_Info);
                            else
                                _wcfPD.PositionDetail_Update(_Info);

                            //Hợp đồng
                            DataSet ds = _wcfLC.LabourContract_GetMaxID(Convert.ToInt32(_emplID[i]));
                            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                int lbId = Globals.Object_GetValue<int>(ds.Tables[0].Rows[0][0]);
                                _lbInfo = _wcfLC.LabourContract_GetInfo(lbId);
                                _lbInfo.DepartmentID = fdept.DepartmentID;

                                //hiepdh: 200815
                                //Sửa lại ko lưu quá trình theo phòng ban nữa, chỉ cần 1 phòng ban mới nhất phụ vụ bảo hiểm
                                if (_lbInfo.ID == 0)
                                    _wcfLC.LabourContract_Insert(_lbInfo);
                                else
                                    _wcfLC.LabourContract_Update(_lbInfo);
                            }
                            else
                            {
                                _lbInfo.DepartmentID = fdept.DepartmentID;
                                _lbInfo.EmployeeID = Convert.ToInt32(_emplID[i]);
                                _lbInfo.PositionID = _Info.PositionID;
                                _lbInfo.IsActive = true;
                                _wcfLC.LabourContract_Insert(_lbInfo);
                            }
                        }
                    }

                    //
                   
                    //reload data
                    _selectedID = "";
                    department_ID = fdept.DepartmentID;
                    LoadData();
                    TreeNode[] tNode = tvBranch.Nodes.Find(department_ID.ToString(), true);
                    if (tNode != null && tNode.Length > 0)
                    {
                        tvBranch.SelectedNode = tNode[0];
                        if (tNode[0].Nodes.Count > 0)
                            tNode[0].Expand();
                        //
                    }
                    //
                    MessageBox.Show("Phân phòng ban thành công!");
                }
            }
            else
            {
                if (dgvEmployeeList.SelectedRows.Count > 0)
                {
                    _FullName = dgvEmployeeList.SelectedRows[0].Cells["FullName"].Value.ToString();
                    _SIBookNo = dgvEmployeeList.SelectedRows[0].Cells["Employee_SIBookNo"].Value.ToString();
                    _EmployeeID = Convert.ToInt32(dgvEmployeeList.SelectedRows[0].Cells["Employee_ID"].Value);
                    if (_PhatSinhBH)
                    {
                        //frmInsurance f = new frmInsurance(0, listRole, _EmployeeID, _IsFactor);
                        //f.ShowDialog(this);
                    }
                    else
                    {
                        dlgResult = DialogResult.OK;
                        this.Close();
                    }
                }
            }
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            txtKeyWord.Text = "";
            if (e.Node.Level == 0)
            {
                branch_ID = Program.intBranchID;
                department_ID = 0;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                branch_ID = Convert.ToInt32(e.Node.Tag);
                department_ID = 0;
                currPage = 0;
                LoadData();
            }
            else if (e.Node.Level == 2)
            {
                department_ID = Convert.ToInt32(e.Node.Tag);
                branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                currPage = 0;
                LoadData();
            }
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnFind_Click(null, null);
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            currPage = 0;
            LoadData();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            if (dgvEmployeeList.SelectedRows.Count > 0)
                dgvEmployeeList_CellDoubleClick(null, null);

        }

        private void frmChooseEmployeeList_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void ChkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            if (ChkCheckAll.Checked)
            {
                for (int i = 0; i < dgvEmployeeList.Rows.Count; i++)
                {
                    dgvEmployeeList.Rows[i].Cells["Check"].Value = true;
                }
            }
            else
            {
                for (int i = 0; i < dgvEmployeeList.Rows.Count; i++)
                {
                    dgvEmployeeList.Rows[i].Cells["Check"].Value = false;
                }
            }
            GetSelectedID();
        }
    }
}

